import {Component, HostListener, OnInit} from '@angular/core';
import { ChatService } from './chat.service';
import {AuthService} from '../services/auth.service';
import {WebSocketMessage} from './WebSocketMessage';

@Component({
  selector: 'app-chat',
  standalone: false,
  templateUrl: './chat.component.html',
  styleUrls: ['./chat.component.css']
})

export class ChatComponent {
  currentUser: any;
  onlineUsers: number = 0;  // 用于存储在线人数
  messages: string[] = [];
  messages_type: string[] = [];
  newMessage: string = '';
  collapsed: boolean = true;

  position = { bottom: 10, right: 10 };
  private isDragging = false;
  private offset = { x: 0, y: 0 };

  constructor(private chatService: ChatService, private authService: AuthService) {
    this.chatService.getMessages().subscribe((data: WebSocketMessage) => {
      const { type, subtype, content, codeHash, masterId , clientId, cursor} = data;

      if (type === 'chat') {
        if (subtype === 'system') {
          this.messages.push(content);
          this.messages_type.push('system');
        } else if (subtype === 'error') {
          this.messages.push(content);
          this.messages_type.push('error');
        } else if (subtype === 'user') {
          this.messages.push(content);
          this.messages_type.push('user');
        } else if (subtype === 'onlineCount') {
          this.onlineUsers = Number(content);
        }
      }
    });

    this.authService.currentUser.subscribe(user => {
      this.currentUser = user;
    });
  }

  send() {
    if (this.newMessage.trim()) {
      this.messages.push(`${this.currentUser.username}: ${this.newMessage}`);
      this.messages_type.push('user');
      this.chatService.sendMessage(`${this.currentUser.username}: ${this.newMessage}`);
      this.newMessage = '';
    }
  }

  toggleCollapse() {
    this.collapsed = !this.collapsed;
  }

  startDrag(event: MouseEvent) {
    if ((event.target as HTMLElement).classList.contains('chat-header')) {
      this.isDragging = true;
      this.offset = {
        x: event.clientX + this.position.right,
        y: event.clientY + this.position.bottom
      };
    }
  }

  @HostListener('document:mousemove', ['$event'])
  onMouseMove(event: MouseEvent) {
    if (this.isDragging) {
      this.position.right = this.offset.x - event.clientX;
      this.position.bottom = this.offset.y - event.clientY;
    }
  }

  @HostListener('document:mouseup')
  onMouseUp() {
    this.isDragging = false;
  }
}
